package com.hectopascal.excel.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.hectopascal.excel.annotation.ExcelPropertyNotNull;
import com.hectopascal.exception.ServiceException;


import java.lang.reflect.Field;

public class ExcelPropertyNotNullListener<T> implements ReadListener<Object> {
    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            //找到类中包含ExcelPropertyNotNull注解的字段
            if (field.isAnnotationPresent(ExcelPropertyNotNull.class)) {
                field.setAccessible(true);
                ExcelPropertyNotNull annotation = field.getAnnotation(ExcelPropertyNotNull.class);
                String errorMessage = annotation.value();
                //得到当前字段的值
                Object fieldValue = null;
                try {
                    fieldValue = field.get(o);
                } catch (IllegalAccessException e) {
                    throw new ServiceException(e.getMessage());
                }
                //判断字段的值是否为空,为空则抛出异常
                if (fieldValue == null || fieldValue.toString().trim().isEmpty()) {
                    throw new ServiceException(errorMessage);
                }
            }
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
